package com.example.androidthreadtest

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    lateinit var changeTextBtn: Button
    lateinit var textView: TextView

    val updateText = 1
    //但是有些时候我们必须在子线程进行一些耗时任务时
    val handler = object : Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message){
            // 在这里可以进行UI操作
            when(msg.what){
                updateText -> textView.text = "Nice to meet you"
            }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        changeTextBtn = findViewById(R.id.changeTextBtn)
        textView = findViewById(R.id.textView)

        changeTextBtn.setOnClickListener {
            thread {
                val msg = Message()
                msg.what = updateText
                handler.sendMessage(msg)
            }
        }

        /*

        // 不能在子线程更新UI，否则会程序崩溃
        // ndroid.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        changeTextBtn.setOnClickListener {
            thread {
                textView.text = "Nice to meet you"
            }
        }*/



    }
}